package Cashier;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginHandler extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	static Map <String,String> users = new HashMap<String, String>();
	static Map <String,String> contents = new HashMap<String, String>();
	
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		PrintWriter writer = resp.getWriter();
		
		String user = req.getParameter("user");
		String pass = req.getParameter("pass");
		String content = req.getParameter("content");
		
		users.put("may", "cm309");
		users.put("eric", "cm309");
		users.put("max", "cm309");
		 
		if (users.containsKey(user)) {
			if (content.isEmpty()) {				
				this.showInfo(writer, "Input Content is Null!");
			} 
			else if (users.get(user).equals(pass)) {
				contents.put(user, content);
				Iterator<Entry<String, String>> it = contents.entrySet().iterator();
				
				writer.print("<html>");
				writer.print("Message has been posted!<br><br>");				
				writer.print("<form metod= 'post' action = 'login.html'>");
				
				while (it.hasNext()) {
					Map.Entry<String, String> me = it.next();
					writer.printf("Guest name: %s<br>", me.getKey());
					writer.printf("Content: %s<br><br>", me.getValue());
				}
				writer.print("<input type = 'submit' value='logout'>");
				writer.print("</form>");

			} else {
				this.showInfo(writer, "Password Incorrect!");
			}
		} else {
			this.showInfo(writer, "user not exist!");
		}
			
	}
	
	private void showInfo(PrintWriter writer, String info)
	{
		writer.print("<html>");
		writer.printf("%s<br>",info);
		writer.print("<input type='button' onclick='history.back()' value='back'>");
		writer.print("</html>");
	}
}
